<script setup lang="ts">
import { ref, onMounted, nextTick, watch, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import dayjs from "dayjs";
import AMapLoader from "@amap/amap-jsapi-loader";
import { getHotelDetail } from "@/api/hotel.js";
import { getHotelRooms } from "@/api/rooms.js";
import { getRoomCount } from "@/api/roominventory.js";
import { addReply, getReplyTree } from "@/api/reply.js";
import { addPost, getAllPosts } from "@/api/post.js";
import ReplyNode from '@/components/ReplyNode.vue';

// ---------------- 酒店 & 房间 ----------------
const route = useRoute();
const router = useRouter();
const hotelId = String(route.params.id);

const checkInDate = ref(dayjs().format("YYYY-MM-DD"));
const checkOutDate = ref(dayjs().add(1, "day").format("YYYY-MM-DD"));

const hotel = ref<any>({});
const facilityList = ref<any[]>([]);
const imageUrlList = ref<any[]>([]);
const hotelPoliciesList = ref<any[]>([]);
const orderCancelRuleList = ref<any[]>([]);
const roomList = ref<any[]>([]);
const Newlatitude = ref<number>();
const Newlongitude = ref<number>();

const roomSection = ref<HTMLElement | null>(null);

// ---------------- 用户信息 ----------------
const userId = ref(Number(localStorage.getItem("userId") || 0));
const userName = ref(localStorage.getItem("userName") || "游客");

// ---------------- 地图 ----------------
const showMap = ref(false);
const mapContainer = ref<HTMLElement | null>(null);
let map: any = null;

const openMap = async () => {
  showMap.value = true;
  await nextTick();
  try {
    const AMap = await AMapLoader.load({
      key: "0dfc4faea6bf061e26e42ab93cf1d835",
      version: "2.0",
      plugins: ["AMap.Scale", "AMap.ToolBar"]
    });

    if (mapContainer.value) {
      map = new AMap.Map(mapContainer.value, {
        viewMode: "3D",
        zoom: 15,
        center: [Number(hotel.value.longitude), Number(hotel.value.latitude)]
      });

      new AMap.Marker({
        position: [Number(hotel.value.longitude), Number(hotel.value.latitude)],
        map,
        title: hotel.value.hotelName
      });
    }
  } catch (err) {
    console.error("地图加载失败", err);
  }
};
const closeMap = () => showMap.value = false;

// ---------------- 获取酒店信息 ----------------
async function getDetail() {
  const res = await getHotelDetail(hotelId);
  hotel.value = res.data.data;
  facilityList.value = hotel.value.facilityNameList || [];
  imageUrlList.value = hotel.value.imageUrlList || [];
  hotelPoliciesList.value = hotel.value.hotelPoliciesList || [];

  const rooms = await getHotelRooms(hotelId);
  roomList.value = rooms.data.data.roomList;
  orderCancelRuleList.value = rooms.data.data.orderCancelRuleList || [];

  Newlatitude.value = hotel.value.latitude;
  Newlongitude.value = hotel.value.longitude;
}

// ---------------- 房间库存 ----------------
async function roomcount() {
  try {
    const res = await getRoomCount(hotelId, checkInDate.value, checkOutDate.value);
    const countList = res?.data?.data ?? [];
    const countMap: Record<string, number> = {};
    countList.forEach(c => {
      if (c?.roomtypeId != null) countMap[String(c.roomtypeId)] = Number(c.minAvailable ?? 0);
    });

    roomList.value = roomList.value.map(item => {
      const copy = Array.isArray(item) ? [...item] : { ...item };
      const roomtypeId = Array.isArray(item) ? item[1] : item.roomtypeId;
      const available = countMap[String(roomtypeId)] ?? 0;
      if (Array.isArray(copy)) copy[7] = available;
      else copy.available = available;
      return copy;
    });
  } catch (err) {
    console.error(err);
  }
}

watch([checkInDate, checkOutDate], ([newIn, newOut]) => {
  if (newIn && newOut) roomcount();
});

function scrollToRooms() {
  roomSection.value?.scrollIntoView({ behavior: "smooth" });
}
function toPay(roomId: any) {
  router.push({
    path: "/toPay",
    query: {
      hotelId,
      roomTypeId: roomId,
      checkInDate: checkInDate.value,
      checkOutDate: checkOutDate.value
    }
  });
}

// ---------------- 评论 ----------------
const postId = ref<string>("");
const replyTree = ref<any[]>([]);
const currentReplyParent = ref<string | null>(null);
const newReplyContent = ref("");

async function loadReplyTree() {
  try {
    const postsRes = await getAllPosts();
    const allPosts = Array.isArray(postsRes?.data?.data)
      ? postsRes.data.data
      : Array.isArray(postsRes?.data)
        ? postsRes.data
        : [];

    const hotelPosts = allPosts.filter(p => String(p.hotelId) === hotelId);
    const replyPromises = hotelPosts.map(p => getReplyTree(p.id ?? p._id));
    const repliesArr = await Promise.all(replyPromises);

    const tree = hotelPosts.map((post, idx) => {
      const repliesRes = repliesArr[idx];
      const replies = Array.isArray(repliesRes?.data?.data)
        ? repliesRes.data.data
        : Array.isArray(repliesRes?.data)
          ? repliesRes.data
          : [];
      return {
        id: String(post.id ?? post._id),
        userName: post.userName || "游客",
        content: post.content || "这位用户没有填写内容",
        createTime: post.createTime ? dayjs(post.createTime).format("YYYY-MM-DD HH:mm:ss") : '',
        children: replies,
        showChildren: false
      };
    });

    replyTree.value = tree;
  } catch (err) {
    console.error("加载评论失败:", err);
    replyTree.value = [];
  }
}

const replyingUserName = computed(() => {
  if (!currentReplyParent.value) return "";
  for (const post of replyTree.value) {
    const queue = [post, ...post.children];
    while (queue.length) {
      const node = queue.shift();
      if (!node) continue;
      if (node.id === currentReplyParent.value) return node.userName;
      if (node.children?.length) queue.push(...node.children);
    }
  }
  return "";
});

function startReplyTo(parentId: string) {
  currentReplyParent.value = parentId;
  newReplyContent.value = "";
  nextTick(() => {
    const ta: any = document.querySelector(".reply-input textarea");
    if (ta) ta.focus();
  });
}

function cancelReply() {
  currentReplyParent.value = null;
  newReplyContent.value = "";
}

async function submitReply() {
  const content = newReplyContent.value.trim();
  if (!content) return;

  try {
    if (currentReplyParent.value) {
      const mainPostId = findPostIdByReplyId(currentReplyParent.value);
      await addReply({
        hotelId,
        postId: mainPostId,
        parentId: currentReplyParent.value,
        userId: userId.value,
        userName: userName.value,
        content
      });
    } else {
      const res = await addPost({
        hotelId,
        userId: userId.value,
        userName: userName.value,
        content
      });
      const newPost = res?.data?.data ?? res?.data;
      postId.value = newPost.id ?? newPost._id;
    }
    newReplyContent.value = "";
    currentReplyParent.value = null;
    await loadReplyTree();
  } catch (err) {
    console.error("提交评论失败:", err);
  }
}

function findPostIdByReplyId(replyId: string) {
  for (const post of replyTree.value) {
    if (post.id === replyId) return post.id;
    if (findReplyInChildren(post.children, replyId)) return post.id;
  }
  return postId.value;
}

function findReplyInChildren(children: any[], replyId: string): boolean {
  for (const child of children) {
    if (child.id === replyId) return true;
    if (child.children?.length && findReplyInChildren(child.children, replyId)) return true;
  }
  return false;
}

// ---------------- 页面初始化 ----------------
onMounted(async () => {
  await getDetail();
  await roomcount();
  await loadReplyTree();
});
</script>


<template>
  <div class="page-container">
    <!-- 酒店头部 -->
    <div class="hotel-header">
      <div>
        <h2>{{ hotel.hotelName }}</h2>
                <div class="address" @click="openMap" style="cursor: pointer; color: #007bff;">
          📍 {{ hotel.city }}市{{ hotel.county }}{{ hotel.street }}
        </div>
      </div>
      <div class="right">
        <div class="price">¥{{ hotel.minRoomPrice }} 起</div>
        <button @click="scrollToRooms">选择房间</button>
      </div>
    </div>

    <!-- 酒店图片 -->
    <div class="hotel-images">
      <div v-for="url in imageUrlList" :key="url.imageId">
        <img :src="`${url.imageUrl}`" alt="酒店图片">
      </div>
    </div>

<!-- 日期选择 -->
<div class="date-box">
  <div class="date-item">
    <label class="date-label">入住时间：</label>
    <el-date-picker
      v-model="checkInDate"
      type="date"
      placeholder="请选择入住日期"
      format="YYYY-MM-DD"
      value-format="YYYY-MM-DD"
      class="date-picker"
    />
  </div>

  <div class="date-item">
    <label class="date-label">退房时间：</label>
    <el-date-picker
      v-model="checkOutDate"
      type="date"
      placeholder="请选择退房日期"
      format="YYYY-MM-DD"
      value-format="YYYY-MM-DD"
      class="date-picker"
    />
  </div>
</div>



    <!-- 酒店设施 -->
    <div class="facilities">
      <h3>酒店设施</h3>
      <div class="facilities-list">
        <span v-for="(item, idx) in facilityList" :key="idx">{{ item }}</span>
      </div>
    </div>

  <!-- 酒店入住政策 -->
  <div class="hotel-policy">
    <h3>入住政策</h3>
    <ul>
      <li v-for="(p, idx) in hotelPoliciesList" :key="idx">
        <span class="policy-content">{{ p }}</span>
      </li>
    </ul>
  </div>

  <!-- 退改政策 -->
    <div class="hotel-policy">
    <h3>退改政策</h3>
    <ul>
      <li v-for="(p, idx) in orderCancelRuleList" :key="idx">
        <span class="policy-content">{{ p }}</span>
      </li>
    </ul>
  </div>

    <!-- 房间列表 -->
    <div ref="roomSection" class="room-section">
      <h3>房间选择</h3>
      <div v-for="(item, idx) in roomList" :key="idx" class="room-card">
        <div class="room-info">
          <img :src="`${item[0]}`" alt="room" />
          <div class="detail">
            <h4>{{ item[2] }}</h4>
            <p>可住 {{ item[3] }} 人</p>
            <p>{{ item[4] }}</p>
            <p>{{ item[5] }}</p>
            
          </div>
        </div>
        <div class="room-prices">
          <!-- 在房间卡片部分替换对应段落 -->
          <!-- 其它不变，只替换剩余显示和按钮 -->
          <div class="price-row">
            <span class="price">¥{{ item[6] }}</span>

            <!-- 兼容 item 既可能是数组也可能是对象的情况 -->
            <p v-if="(Array.isArray(item) ? item[7] : item.available) > 0">
              剩余 {{ Array.isArray(item) ? item[7] : item.available }} 间
            </p>
            <p v-else class="sold-out">已售罄</p>
            <!-- <p>房型id{{ item[1] }}</p> -->
            <button
              :disabled="(Array.isArray(item) ? item[7] : item.available) <= 0"
              :class="{ 'btn-disabled': (Array.isArray(item) ? item[7] : item.available) <= 0 }"
              @click="toPay(item[1])"
            >
              预订
            </button>

          </div>  
        </div>
      </div>
    </div>
  </div>

  <!-- 评论区 -->
<div class="reply-section">
  <div class="reply-input">
    <textarea v-model="newReplyContent" placeholder="写下你的评论..."></textarea>
    <div class="reply-actions">
      <span v-if="currentReplyParent" class="replying-text">
        正在回复 {{ replyingUserName }}
        <button class="cancel-reply" @click="cancelReply">取消</button>
      </span>
      <button class="send-btn" @click="submitReply">发表</button>
    </div>
  </div>

  <ul v-if="replyTree.length" class="reply-tree">
    <ReplyNode 
      v-for="reply in replyTree" 
      :key="reply.id" 
      :node="reply" 
      @reply="startReplyTo" />
  </ul>
  <p v-else>暂无评论，快来发表第一条吧~</p>
</div>


<!-- 地图弹窗 -->
<div v-if="showMap" class="map-modal">
  <div class="map-box">
    <div class="map-header">
      <h3>{{ hotel.hotelName }} 位置</h3>
      <button @click="closeMap">关闭</button>
    </div>
    <div ref="mapContainer" class="map-container"></div>
  </div>
</div>
</template>

<style scoped>

/* 评论区域整体 */
.reply-section {
  background: #fff;
  margin: 20px auto 0; /* 上边距20px，水平居中 */
  padding: 16px;
  border: 1px solid #eee;
  border-radius: 6px;
  max-width: 1200px;   /* 和页面主体最大宽度一致 */
  box-sizing: border-box;
}

/* 评论输入框 */
.reply-input {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}

.reply-input textarea {
  width: 100%;
  min-height: 80px;
  resize: vertical;
  padding: 8px 12px;
  font-size: 14px;
  border: 2px solid #acacad;
  border-radius: 6px;
  outline: none;
  transition: all 0.2s;
  box-sizing: border-box;
}

.reply-input textarea:focus {
  border-color: #0071eb;
  box-shadow: 0 0 6px rgba(0, 113, 235, 0.2);
}

.reply-input button {
  align-self: flex-end;
  margin-top: 8px;
  background: #0071eb;
  color: #fff;
  border: none;
  padding: 6px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}
.reply-input button:hover {
  background: #005bb5;
}

/* 评论树 */
.reply-tree {
  list-style: none;
  padding: 0;
  margin: 0;
}

/* 单条评论 */
.reply-item {
  padding: 10px 0;
  border-bottom: 1px dashed #ddd;
  font-size: 14px;
  max-width: 100%;   /* 防止评论溢出 */
  box-sizing: border-box;
}

/* 用户名和时间 */
.reply-item .header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
  font-weight: 600;
  color: #0071eb;
}

.reply-item .text {
  color: #444;
  margin-bottom: 6px;
}

/* 操作按钮 */
.reply-item .actions button {
  background: transparent;
  border: none;
  color: #0071eb;
  cursor: pointer;
  font-size: 13px;
  padding: 0;
}
.reply-item .actions button:hover {
  text-decoration: underline;
}

/* 子评论缩进 */
.reply-item ul {
  list-style: none;
  padding-left: 20px;
  margin-top: 8px;
  border-left: 2px solid #f0f0f0;
}

/* 展开/收起子评论按钮 */
.reply-item > button {
  background: transparent;
  border: none;
  color: #0071eb;
  cursor: pointer;
  font-size: 13px;
  margin-top: 4px;
  padding: 0;
}
.reply-item > button:hover {
  text-decoration: underline;
}

/* 回复正在进行状态 */
.replying-text .cancel-reply {
  background: transparent;
  border: none;
  color: #e60023;
  cursor: pointer;
  font-size: 12px;
  margin-left: 8px;
}

.replying-text .cancel-reply:hover {
  text-decoration: underline;
}


/* ✅ 新增地图样式 */
.map-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.map-box {
  width: 800px;
  height: 600px;
  background: #fff;
  border-radius: 10px;
  overflow: hidden;
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: #007bff;
  color: white;
}

.map-container {
  width: 100%;
  height: calc(100% - 50px);
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 16px;
  background: #f7f8fa;
}

/* 头部 */
.hotel-header {
  display: flex;
  justify-content: space-between;
  background: #fff;
  padding: 20px;
  border-radius: 10px 10px 0 0;
  border: 1px solid #eee;
}

.hotel-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.hotel-header .address {
  font-size: 14px;
  color: #666;
}

.price {
  font-size: 22px;
  color: #e60023;
  font-weight: bold;
}

.hotel-header button {
  background: #0071eb;
  color: #fff;
  border: none;
  padding: 10px 20px;
  margin-top: 8px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}
.hotel-header button:hover {
  background: #005bb5;
}

/* 酒店图片区域 */
.hotel-images {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr; /* 主图+两列小图 */
  grid-auto-rows: 240px; /*  每行高度从150px放大到240px */
  grid-gap: 10px; /*  间距略放大 */
  background: #fff;
  padding: 10px;
  border: 1px solid #ddd;
  border-top: none;
  border-radius: 10px;
}


.hotel-images img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 10px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

/* 鼠标悬停放大效果 */
.hotel-images img:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.15);
}


/* 日期选择区域整体 */
.date-box {
  background: #fff;
  margin-top: 20px;
  padding: 24px;
  display: flex;
  gap: 40px;
  align-items: center;
  border: 2px solid #acacad !important; /* 边框加深，更明显 */
  border-radius: 8px;
  /* box-shadow: 0 2px 6px rgba(0, 113, 235, 0.1); */
}

/* 单个日期选择项 */
.date-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  flex: 1;
}

/* 标签文字样式 */
.date-label {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 6px;
}

/* 日期选择器本体 */
.date-picker {
  width: 260px;             /*  放大输入框 */
  height: 44px;
  font-size: 16px;
}

/* 调整 Element Plus 输入框样式 */
:deep(.el-input__wrapper) {
  border: 2px solid #acacad !important; /*  边框颜色加深 */
  border-radius: 6px !important;
  box-shadow: none !important;
  transition: all 0.2s;
}

:deep(.el-input__wrapper:hover),
:deep(.el-input__wrapper.is-focus) {
  border-color:  #acacad !important; /*  聚焦时颜色更深 */
  box-shadow: 0 0 6px rgba(0, 91, 181, 0.2);
}


/* 酒店设施 */
.facilities {
  background: #fff;
  margin-top: 16px;
  padding: 16px;
  border: 1px solid #eee;
  border-radius: 6px;
}
.facilities h3 {
  margin-bottom: 12px;
  font-size: 18px;
  font-weight: 600;
  border-left: 4px solid #0071eb; /* 蓝色竖杠 */
  padding-left: 8px;              /* 与文字间距 */
}

.facilities-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px 30px;
  font-size: 14px;
}
/* 入住政策 */
.hotel-policy {
  background: #fff;
  margin-top: 16px;
  padding: 16px 20px;
  border: 1px solid #eee;
  border-radius: 6px;
}

.hotel-policy h3 {
  font-size: 18px;
  margin-bottom: 12px;
  font-weight: 600;
  border-left: 4px solid #0071eb;
  padding-left: 8px;
}

.hotel-policy ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.hotel-policy li {
  padding: 8px 0;
  border-bottom: 1px dashed #ddd;
  font-size: 14px;
  color: #444;
}

.hotel-policy li:last-child {
  border-bottom: none;
}

.policy-type {
  font-weight: 600;
  color: #0071eb;
  margin-right: 4px;
}

.policy-content {
  color: #666;
}


/* 房间 */
.room-section {
  margin-top: 20px;
}
.room-section h3 {
  margin-bottom: 10px;
  font-size: 18px;
}
.room-card {
  background: #fff;
  border: 1px solid #eee;
  border-radius: 6px;
  margin-bottom: 20px;
  overflow: hidden;
}
.room-info {
  display: flex;
  gap: 12px;
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}
.room-info img {
  width: 140px;
  height: 90px;
  object-fit: cover;
  border-radius: 6px;
}
.room-info .detail h4 {
  margin: 0 0 6px 0;
  font-size: 16px;
}
.room-info .detail p {
  margin: 2px 0;
  font-size: 14px;
  color: #666;
}

/* 房价 */
.room-prices {
  display: flex;
  flex-direction: column;
}
.price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
}
.price-row .desc {
  font-size: 14px;
}
.price-row .price {
  font-size: 18px;
  font-weight: bold;
  color: #e60023;
}
.price-row button {
  background: #0071eb;
  color: #fff;
  border: none;
  padding: 6px 16px;
  border-radius: 6px;
  cursor: pointer;
}
.price-row button:hover {
  background: #005bb5;
}
/* 已售罄红色字体 */
.sold-out {
  color: #e60023; /* 红色，与价格保持一致风格 */
  font-weight: bold;
}

/* 禁用状态的预订按钮 */
.btn-disabled {
  background: #ccc !important;
  color: #666 !important;
  cursor: not-allowed;
  box-shadow: none !important;
}

</style>
